import type { PostItem } from '../post/type'
import type { Role } from '../role/type'
import type { DeptTree, IProfile, IUpdateUserProfile, IUserInfoRes, User, UserParams, UserQueryParams } from './type'
import { http } from '@/utils/request'

const prefix = import.meta.env.VITE_API_SYS

// 查询用户信息
export function systemUserProfile() {
	return http.get<IProfile>(`${prefix}/user/profile`)
}
// 修改用户个人信息
export function updateUserProfile(data: IUpdateUserProfile) {
	return http.put(`${prefix}/user/profile`, data)
}
// 用户密码重置
export function updateUserPwd(oldPassword: string, newPassword: string) {
	return http.put(`${prefix}/user/profile/updatePwd`, {
		oldPassword,
		newPassword
	})
}

// 用户头像上传
export function uploadAvatar(data: FormData) {
	return http.postFile<{ imgUrl: string }>(`${prefix}/user/profile/avatar`, data, {
		headers: { 'Content-Type': 'multipart/form-data' }
	})
}

// 用户状态修改
export function changeUserStatus(userId: number, status: number) {
	return http.put(`${prefix}/user/changeStatus`, {
		userId,
		status
	})
}

// 查询用户个人信息
export function getUserProfile() {
	return http.get(`${prefix}/user/profile`)
}

// 查询授权角色
export function getAuthRole(userId: string) {
	return http.get<{ roles: Role[]; user: User }>(`${prefix}/user/authRole/${userId}`)
}

// 保存授权角色
export function updateAuthRole(data: { userId: number; roleIds: string }) {
	return http.put(`${prefix}/user/authRole`, data)
}

// 查询部门下拉树结构
export function deptTreeSelect() {
	return http.get<DeptTree[]>(`${prefix}/user/deptTree`)
}

// 查询用户列表
export function listUser(params: UserQueryParams & Page) {
	return http.get<ResPage<User[]>>(`${prefix}/user/list`, params)
}

// 查询用户详细
export function getUser(userId: string = '') {
	return http.get<{ posts: PostItem[]; roles: Role[]; data: User; postIds: number[]; roleIds: number[] }>(
		`${prefix}/user/${userId}`
	)
}

// 新增用户
export function addUser(data: UserParams) {
	return http.post(`${prefix}/user`, data)
}

// 修改用户
export function updateUser(data: UserParams) {
	return http.put(`${prefix}/user`, data)
}

// 删除用户
export function delUser(userId: string) {
	return http.delete(`${prefix}/user/${userId}`)
}

// 用户密码重置
export function resetUserPwd(userId: number, password: string) {
	return http.put(`${prefix}/user/resetPwd`, {
		id: userId,
		password
	})
}

// 用户管理导出
export function userExport(data: UserQueryParams & Page) {
	return http.postFile<ExportResponse>(`${prefix}/user/export`, data, {
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		responseType: 'blob'
	})
}

// 用户管理导入地址
export const USER_UPLOAD_URL = import.meta.env.VITE_API_URL + `${prefix}/user/importData`
// 下载地址
export function userImportTemplate() {
	return http.postFile<ExportResponse>(`${prefix}/user/importTemplate`, undefined, {
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		responseType: 'blob'
	})
}

export function getUserInfo() {
	return http.get<IUserInfoRes>(`${prefix}/user/getInfo`)
}
